var express = require("express");
var router = express.Router();
const jwt = require("jsonwebtoken");
const {PWD_SALT, PRIVATE_KEY, JWT_EXPIRED} = require("../utils/constant");
const {md5,decoded} = require("../utils/index")
const {login, findUser} = require("../service/user")
const Result = require("../models/Result")

router.get("/hello", function (req, res) {
    res.send("I'm user,welcome to me");
});

router.post("/login", function (req, res) {
    let {username, password} = req.body;
    password = md5(`${password}${PWD_SALT}`);
    login(username, password).then((user) => {
        if (!user) {
            new Result("登录失败").fail(res)
        } else {
            const token = jwt.sign({username}, PRIVATE_KEY, {
                expiresIn: JWT_EXPIRED,
            })
            new Result({token, user}, "操作成功", 1).success(res)
        }
    })
});

router.get("/info", function (req, res) {
    const decode = decoded(req);
    if (decode && decode.username) {
        findUser(decode.username).then((user) => {
            if (user) {
                console.log(user);
                user.roles = [user.role];
                new Result(user, "用户信息查询成功").success(res);
            } else {
                new Result("用户信息查询失败").fail(res);
            }
        });
    } else {
        new Result("用户信息查询失败").fail(res);
    }
});

module.exports = router;